<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            ①确定终止条件
            */
            var solveNQueens = function (n) {
                const chessboard = new Array(n).fill().map(() => new Array(n).fill("."))

                function isValid(row, col, chessboard, n) {
                    //判断是否会同列
                    for (let i = 0; i < row; i++) {
                        if (chessboard[i][col] == "Q") return false
                    }
                    //判断45
                    for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
                        if (chessboard[i][j] == "Q") return false
                    }
                    for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
                        if (chessboard[i][j] == "Q") return false
                    }
                    return true
                }

                const res = []
                function transform(chessboard) {
                    return chessboard.map((item) => {
                        return item.join("")
                    })
                }

                function backTracking(row) {
                    if (row == n) {
                        return res.push(transform(chessboard))
                    }
                    //判断每一行中的每一列是否满足条件
                    for (let col = 0; col < n; col++) {
                        if (isValid(row, col, chessboard, n)) {
                            chessboard[row][col] = "Q"
                            backTracking(row + 1)
                            chessboard[row][col] = "."
                        }
                    }
                }
                backTracking(0)
                return res
            }
        </script>
    </body>
</html>
